using System;
using System.Web;

using NHibernate;
using NHibernate.Cfg;

namespace Wayloop.Fusion.Data.HttpModules
{
    public sealed class NHibernateSessionManager
    {
        private static readonly string SessionKey = "CONTEXT_SESSION";
        //private static readonly string TransactionKey = "CONTEXT_TRANSACTION";
        private ISessionFactory sessionFactory;

        public static ISession Session
        {
            get
            {
                ISession session = HttpContext.Current.Items[SessionKey] as ISession;

                if (session == null)
                {
                    session = Instance.SessionFactory.OpenSession();

                    if (session == null)
                        throw new ApplicationException("ISession could not be opened");

                    HttpContext.Current.Items[SessionKey] = session;
                }

                return session;
            }
        }

        private static NHibernateSessionManager Instance
        {
            get { return Nested.instance; }
        }

        private ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    Configuration configuration = new Configuration();

                    configuration.Configure();
                    sessionFactory = configuration.BuildSessionFactory();

                    if (sessionFactory == null)
                        throw new ApplicationException("ISessionFactory could not be initialized.");
                }

                return sessionFactory;
            }
        }

        private class Nested
        {
            internal static readonly NHibernateSessionManager instance = new NHibernateSessionManager();


            static Nested()
            {
                // Force correct compiler initialization
            }
        }
    }
}